package com.android.flowoflife.hardware;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.util.Log;

import com.android.flowoflife.IFlowOfLifeConstants;

public class SocketCameraAccess extends AbstractCameraAccess {
	private static final int SOCKET_TIMEOUT = 1000;

	private String ip;
	private int port;

	public SocketCameraAccess(String ip, int port, int width, int height) {
		super(width, height);
		this.ip = ip;
		this.port = port;
	}

	@Override
	public void takePicture(ShutterCallback shutterCallback, PictureCallback rawPictureCallback, PictureCallback jpegPictureCallback) {
		Socket socket = null;
		InputStream in = null;
		
		try {
			socket = new Socket();
			socket.bind(null);
			socket.setSoTimeout(SOCKET_TIMEOUT);
			socket.connect(new InetSocketAddress(ip, port), SOCKET_TIMEOUT);
			
			in = socket.getInputStream();
			Bitmap bitmap = BitmapFactory.decodeStream(in);
			bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
			
			shutterCallback.onShutter();
			rawPictureCallback.onPictureTaken(null, null);
			
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, 75, outputStream);;
			jpegPictureCallback.onPictureTaken(outputStream.toByteArray(), null);			
		} catch (Exception e) {
			Log.i(IFlowOfLifeConstants.LOG_TAG, "Failed to obtain image over network", e);
		} finally {
			if (in != null) try {
				in.close();
			} catch (IOException e) {
				/* ignore */
			}
			if (socket != null) try {
				socket.close();
			} catch (IOException e) {
				/* ignore */
			}
		}
	}

}
